<template>
  <Row :gutter="5" style="margin-top: -15px">
    <Col :span="16">
      <Table :showHeader="false" :columns="companyColumns" :scroll="{ x: 600, y: contentHeight - 8 }" :pagination="false" :data-source="companies" size="small" bordered></Table>
    </Col>
    <Col :span="8">
      <Table :columns="columns" :scroll="{ x: 200, y: contentHeight - 45 }" :pagination="false" :data-source="stocks" size="small" bordered>
        <template #bodyCell="{ column, record, index }">
          <div v-if="column.key == 'content'" class="content">
            <h3>
              <router-link :to="`/share/${record.quote.symbol}/Detail?title=${record.quote.name}`">{{ record.quote.name }}({{ record.quote.code }})</router-link>
              <b :class="getClass(record.quote.chg)">￥{{ record.quote.current }}</b>
              <b :class="getClass(record.quote.chg)">{{ record.quote.chg }}</b>
              <b :class="getClass(record.quote.chg)">{{ record.quote.percent }}%</b>
              <Button v-if="index != 0" @click="addShare(record.quote)" type="primary" danger size="small" shape="circle"><FileAddOutlined /></Button>
            </h3>
            <label>
              当前价<span>{{ record.quote.current }}</span>
            </label>
            <label>
              最高<span>{{ record.quote.high }}</span>
            </label>
            <label>
              今开<span>{{ record.quote.open }}</span>
            </label>
            <label>
              涨停<span>{{ record.quote.limit_up }}</span>
            </label>
            <label>
              跌停<span>{{ record.quote.limit_down }}</span>
            </label>
            <label>
              成交量<span>{{ friendlyNumbers(record.quote.volume) }}</span>
            </label>
            <label>
              成交额<span>{{ friendlyNumbers(record.quote.amount) }}</span>
            </label>
            <label>
              量比<span>{{ record.quote.volume_ratio }}%</span>
            </label>
            <label>
              每股收益<span>{{ record.quote.eps }}</span>
            </label>
            <label>
              每股净资产<span>{{ record.quote.navps }}</span>
            </label>
            <label>
              总股本<span>{{ friendlyNumbers(record.quote.total_shares) }}</span>
            </label>
            <label>
              总市值<span>{{ friendlyNumbers(record.quote.market_capital) }}</span>
            </label>
            <label>
              流通股<span>{{ friendlyNumbers(record.quote.float_shares) }}</span>
            </label>
            <label style="width: 66.66666%">
              流通股市值<span>{{ friendlyNumbers(record.quote.float_market_capital) }}</span>
            </label>
            <label>
              52周最高<span>{{ record.quote.high52w }}</span>
            </label>
            <label>
              52周最低<span>{{ record.quote.low52w }}</span>
            </label>
          </div>
        </template>
      </Table>
    </Col>
  </Row>
</template>
<script setup>
  import dayjs from 'dayjs';
  import { ref, watchEffect, h, inject, reactive } from 'vue';
  import { Row, Col, Table, Button } from 'ant-design-vue';
  import { FileAddOutlined } from '@ant-design/icons-vue';
  import { fillDatas, friendlyNumbers } from '@/libs/helpers.js';

  const mappings = [
    { title: '公司名称', key: 'org_name_cn' },
    { title: '曾用名', key: 'pre_name_cn' },
    { title: '所属省份', key: 'provincial_name' },
    { title: '实际控制人', key: 'actual_controller' },
    {
      title: '所有制性质名称',
      key: 'classi_name',
      getValue: item => {
        return `${item.classi_name} / ${item.affiliate_industry.ind_name}`;
      }
    },
    { title: '主营业务', key: 'main_operation_business' },
    { title: '经营范围', key: 'operating_scope' },
    { title: '公司简介', key: 'org_cn_introduction' },
    { title: '董事长', key: 'chairman' },
    { title: '法人代表', key: 'legal_representative' },
    { title: '总经理', key: 'general_manager' },
    { title: '董秘', key: 'secretary' },
    { title: '成立日期', getValue: item => dayjs(item.established_date).format('YYYY-MM-DD') },
    { title: '注册资本(CNY)', getValue: item => friendlyNumbers(item.reg_asset) },
    { title: '员工人数', key: 'staff_num' },
    { title: '管理层人数', key: 'executives_nums' },
    { title: '上市日期', getValue: item => dayjs(item.listed_date).format('YYYY-MM-DD') },
    { title: '发行量', getValue: item => friendlyNumbers(item.actual_issue_vol) },
    { title: '发行价格', key: 'issue_price' },
    { title: '募集资金', getValue: item => friendlyNumbers(item.actual_rc_net_amt) },
    { title: '发行市盈率', key: 'pe_after_issuing' },
    { title: '网上中签率', getValue: item => (item.online_success_rate_of_issue || 0).toFixed(2) + '%' },
    { title: '联系电话', key: 'telephone' },
    { title: '邮政编码', key: 'postcode' },
    { title: '传真', key: 'fax' },
    { title: '电子邮箱', key: 'email' },
    {
      title: '公司网址',
      key: 'org_website',
      getValue: item => {
        let site = (item.org_website || '').split(';')[0];

        return `http://${site}`;
      }
    },
    { title: '注册地址', key: 'reg_address_cn' },
    { title: '办公地址', key: 'office_address_cn' }
  ];

  const props = defineProps({
    code: {
      type: String
    },
    contentHeight: {
      type: Number
    }
  });

  const $http = inject('$http');
  const $modal = inject('$modal');
  const $message = inject('$message');

  const stocks = ref([]);
  const companyColumns = ref([
    {
      title: '标签',
      dataIndex: 'title',
      width: 160,
      align: 'right',
      customRender: ({ record }) => {
        return h('strong', record.title);
      }
    },
    {
      title: '值',
      dataIndex: 'value',
      customRender: ({ record }) => {
        if (((record.value || '') + '').indexOf('http') == 0) {
          return h(
            'a',
            {
              target: '_blank',
              href: record.value
            },
            record.value
          );
        }

        return record.value;
      }
    }
  ]);
  const companies = ref([]);

  const columns = reactive([
    {
      title: '所属板块',
      key: 'content'
    }
  ]);

  function loadCompany() {
    if (!props.code) {
      return;
    }

    let url = `/api/shares/${props.code}/company`;

    getStock();

    $http.get(url).then(res => {
      getStocks(res.data.affiliate_industry.ind_code);

      companies.value = mappings.map(m => {
        if (m.getValue && typeof m.getValue == 'function') {
          return {
            title: m.title,
            value: m.getValue(res.data)
          };
        } else {
          return {
            title: m.title,
            value: res.data[m.key]
          };
        }
      });
    });
  }

  function getStock() {
    $http.get(`/api/shares/${props.code}/stock`).then(res => {
      stocks.value.unshift(res.data);
    });
  }

  function getStocks(stockCode) {
    if (!stockCode) {
      return;
    }

    $http.get(`/api/shares/${stockCode}/stocks`).then(res => {
      stocks.value.push(...res.data.items);
    });
  }

  function getClass(val) {
    return val >= 0 ? 'up' : 'down';
  }

  function addShare(info) {
    $modal.confirm({
      title: '提醒',
      content: '是否确定关注该股票？',
      onOk: () => {
        let rawInfo = {};

        rawInfo.Code = info.code;
        rawInfo.Name = info.name;
        rawInfo.CreatedOn = dayjs().format('YYYY-MM-DD HH:mm:ss');

        if (!rawInfo.Code) {
          $message.warning('股票编号不能为空！');

          return;
        }

        if (!rawInfo.Name) {
          $message.warning('股票名称不能为空！');

          return;
        }

        if (rawInfo.Code.indexOf('00') == 0 || rawInfo.Code.indexOf('200') == 0 || rawInfo.Code.indexOf('30') == 0) {
          rawInfo.Code = 'sz' + rawInfo.Code;
        } else if (rawInfo.Code.indexOf('60') == 0 || rawInfo.Code.indexOf('900') == 0) {
          rawInfo.Code = 'sh' + rawInfo.Code;
        }

        $http.post('/api/shares/save', rawInfo).then(res => {
          if (res.success) {
            $message.success('关注成功！');
          } else {
            $message.error('关注失败，错误详情：' + res.message);
          }
        });
      }
    });
  }

  watchEffect(() => {
    stocks.value.length = 0;

    loadCompany();
  });
</script>
<style lang="less" scoped>
  .content {
    width: 100%;
    display: inline-block;
    user-select: none;

    .up {
      color: #c1232b;
    }

    .down {
      color: green;
    }

    > h3 {
      padding: 0;
      margin: 0;
      padding-bottom: 2px;
      margin-top: -5px;
      margin-bottom: 5px;
      border-bottom: solid 1px #ccc;

      > strong {
        user-select: all;
        cursor: default;
        padding-right: 10px;
      }

      > b {
        font-size: 0.918em;
        padding-right: 10px;

        &:first-of-type {
          font-size: 1.2em;
        }
      }

      > button {
        float: right;
        margin-top: 3px;
        margin-right: 5px;
      }
    }

    > label {
      width: 33.33333%;
      line-height: 1;
      display: inline-block;
      font-weight: bold;
      white-space: nowrap;
      overflow: hidden;

      > span {
        font-weight: normal;
        padding-left: 5px;
      }
    }
  }
</style>
